import axios from 'axios';
import {useRouter} from "vue-router";
import  router from "../router"

// 请求超时时间
axios.defaults.timeout = 100000;
// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json;';
axios.interceptors.request.use( /*这是拦截器设置tokne*/
    config => {
        if (config.url.includes("signIn")) {
            return config;
        }

        let token = localStorage.getItem("token");

        if (token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.token = `${token}`;
        }

        let tokenExpired = localStorage.getItem("expiredTime");
        let now = new Date().getTime();
        console.log(tokenExpired)
        if (now > Number(tokenExpired)) {
            router.push('/login');
        }

        return config;
    },
    err => {
        console.log(err)
        return Promise.reject(err);
    });
axios.interceptors.response.use(
    res => {

        if (res.data.code === 115) {
            console.log("过期了")
            localStorage.removeItem("token");
            // window.location.href = "/login"
            console.log(localStorage.getItem("ms_username"))
            router.push('/login');
        }
        return res;
    },
    error => {

    }
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params,token) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params, config) {
    return new Promise((resolve, reject) => {
        axios.post(url, params, config)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

/**
 * 多个请求全部成功
 * @param {Array} arr [待执行的函数]
 */

// export function all(arr){
// 	return axios.all( arr ).then(axios.spread( (acct,perms) => {
// 		//
// 	}))
// }
